URL Dispatch
with
Django

Manish Patel

Aug 21, 2023

URL dispatch, URL patterns, and corresponding views

Step 1: Set Up a Django Project

If you haven’t already, install Django:

pip install Django

Create a new Django project:

django-admin startproject URLDemo
cd URLDemo

Step 2: Create an App

Now, let’s create a new app within the project:

python manage.py startapp demoapp
  • Register app in settings

Step 3: Define URL Patterns

In the demoapp directory, create a file named urls.py to define your URL patterns:


from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('about/', views.about, name='about'),
    path('contact/', views.contact, name='contact'),
]

Step 4: Create Views

In the same demoapp directory, modify the file named views.py to define your views:

from django.shortcuts import render
from django.http import HttpResponse

def home(request):
    return HttpResponse("Welcome to the Home Page")

def about(request):
    return HttpResponse("This is the About Page")

def contact(request):
    return HttpResponse("Contact us at contact@example.com")

> FOR SERVING HTML FILES

from django.shortcuts import render

def home(request):
    return render(request, 'home.html')

def about(request):
    return render(request, 'about.html')

def contact(request):
    return render(request, 'contact.html')

Step 5: Wire Up the App

In the URLDemo project directory, open the urls.py file and include the app’s URLs:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('demoapp.urls')),
]

Step 6: Run the Server

Now you can run the development server:

python manage.py runserver

Visit these URLs in your browser to see the different views:

  • Home: http://127.0.0.1:8000/
  • About: http://127.0.0.1:8000/about/
  • Contact: http://127.0.0.1:8000/contact/